package cm.mefobe.android.telecomcost.dialog;

import cm.mefobe.android.telecomcost.R;
import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.activities.VoiceRateListActivity;
import cm.mefobe.android.telecomcost.entities.Destination;
import cm.mefobe.android.telecomcost.entities.TimeIntervall;
import cm.mefobe.android.telecomcost.entities.TimePeriod;
import cm.mefobe.android.telecomcost.entities.VoiceRate;
import cm.mefobe.android.telecomcost.view.AmountView;
import cm.mefobe.android.telecomcost.view.DaysPickerView;
import cm.mefobe.android.telecomcost.view.DestinationView;
import cm.mefobe.android.telecomcost.view.TariffingIntervallView;
import cm.mefobe.android.telecomcost.view.TimeIntervallView;
import cm.mefobe.android.telecomcost.view.TimeIntervallViewLabelTop;
import cm.mefobe.android.telecomcost.view.TimePickerView;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class VoiceRateWizard extends Dialog {

	private Context _context;
	private TimePickerView startTimePicker;
	private TimePickerView endTimePicker;
	private TimeIntervallView freeTimeView;
	private TariffingIntervallView tariffingIntervallView;
	private DaysPickerView daysPickerView;
	private Button btnNext;
	private Button btnPrevious;
	private Button btnClose;
	private ViewFlipper flipper;
	private AmountView connectionCharges;
	private AmountView fees;
	private AmountView minimumCharges;
	private AmountView maximumCharges;
	private int viewIndex = 0;
	private TimeIntervallView dureeMax;
	private TimeIntervallView extraIntervallstart;
	private TimeIntervallView extraTariffingIntervall;
	private AmountView extraFees;
	private DestinationView destinationView;
	private VoiceRate _voiceRate;
	private static final int VIEW_DATES = 0;
	private static final int VIEW_CHARGES = 1;
	private static final int VIEW_EXTRA_TARIFF = 2;
	private static final int VIEW_DESTINATION = 3;

	/**
	 * @param context
	 * @param cancelable
	 * @param cancelListener
	 */
	public VoiceRateWizard(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		_context = context;
	}

	/**
	 * @param context
	 * @param theme
	 */
	public VoiceRateWizard(Context context, int theme) {
		super(context, theme);
		_context = context;
	}

	public VoiceRateWizard(Context context) {
		super(context);
		_context = context;
	}

	public VoiceRateWizard(Context context, VoiceRate voiceRate) {
		super(context);
		_context = context;
		_voiceRate = voiceRate;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("VoiceRateWizard", "Creating the VoiceRateWizard...");
		super.onCreate(savedInstanceState);

		setContentView(R.layout.voice_rate_wizard);
		setTitle("Edit a Voice Rate");

		btnNext = (Button) findViewById(R.id.btnNext);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		btnClose = (Button) findViewById(R.id.btnClose);

		flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);

		startTimePicker = (TimePickerView) findViewById(R.id.timePicker1);
		endTimePicker = (TimePickerView) findViewById(R.id.timePicker2);
		freeTimeView = (TimeIntervallView) findViewById(R.id.timeIntervallView1);
		tariffingIntervallView = (TariffingIntervallView) findViewById(R.id.tariffingIntervallView);
		daysPickerView = (DaysPickerView) findViewById(R.id.daysPicker1);

		freeTimeView.setLabel("Free Time       ");
		freeTimeView.setTimeIntervall(new TimeIntervall(TimePeriod.SECOND, 0));
		tariffingIntervallView.setLabel("Tarif intervall ");
		startTimePicker.setLabel("Start Time       ");
		endTimePicker.setLabel("End Time         ");

		fees = (AmountView) findViewById(R.id.amount1);
		connectionCharges = (AmountView) findViewById(R.id.amount2);
		minimumCharges = (AmountView) findViewById(R.id.amount3);
		maximumCharges = (AmountView) findViewById(R.id.amount4);

		connectionCharges.setLabel("Connection charges ");
		minimumCharges.setLabel("Minimum charges    ");
		maximumCharges.setLabel("Maximum charges    ");

		dureeMax = (TimeIntervallViewLabelTop) findViewById(R.id.dureeMax);
		extraIntervallstart = (TimeIntervallViewLabelTop) findViewById(R.id.extraIntervallstart);
		extraTariffingIntervall = (TimeIntervallViewLabelTop) findViewById(R.id.extraTariffingIntervall);
		extraFees = (AmountView) findViewById(R.id.amount41);

		dureeMax.setLabel("Maximum duration of the tariff");
		extraIntervallstart.setLabel("Extra free time");
		extraTariffingIntervall.setLabel("Extra tariffing Intervall");
		extraFees.setLabel("Extra fees");

		destinationView = (DestinationView) findViewById(R.id.destinationView);

		btnClose.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				closeDialog();
			}
		});

		btnNext.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showNextView();
			}
		});

		btnPrevious.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showPreviousView();
			}
		});

		Log.i("VoiceRateWizard", "VoiceRateWizard ohne bundle created....");
	}

	private boolean checkAmounts() {
		if (fees.getAmount() < 0) {
			Toast.makeText(_context, "Please set the fees for this tariff", 3)
					.show();
			return false;
		}

		if (connectionCharges.getAmount() < 0) {
			Toast.makeText(_context,
					"Please set the connection charges for this tariff", 3)
					.show();
			return false;
		}

		if (minimumCharges.getAmount() < 0) {
			Toast.makeText(_context,
					"Please set the minimum charges for this tariff", 3).show();
			return false;
		}

		if (maximumCharges.getAmount() < 0) {
			Toast.makeText(_context,
					"Please set the maximum charges for this tariff", 3).show();
			return false;
		}

		return true;
	}

	protected void showNextView() {
		switch (viewIndex) {
		case VIEW_DATES:
			if (checkDates()) {
				prepareViewCharges();
				flipper.showNext();
				viewIndex++;
			}
			break;
		case VIEW_CHARGES:
			if (checkAmounts()) {
				prepareViewExtraCharges();
				flipper.showNext();
				viewIndex++;
			}
			break;
		case VIEW_EXTRA_TARIFF:
			if (checkExtraTariff()) {
				prepareViewDestination();
				flipper.showNext();
				viewIndex++;
			}
			break;
		case VIEW_DESTINATION:
			saveVoiceRate();
			break;
		}
	}

	private void saveVoiceRate() {
		Destination dest = destinationView.getDestination();

		_voiceRate = _voiceRate == null ? new VoiceRate() : _voiceRate;
		_voiceRate.setTariffingIntervall(tariffingIntervallView
				.getTimeIntervall());
		_voiceRate.setStartTime(startTimePicker.getTime());
		_voiceRate.setMinimumCharges(minimumCharges.getAmount());
		_voiceRate.setMaximumCharges(maximumCharges.getAmount());
		_voiceRate.setIntervallstart(freeTimeView.getTimeIntervall());
		_voiceRate.setFees(fees.getAmount());
		_voiceRate.setExtraTariffingIntervall(extraTariffingIntervall
				.getTimeIntervall());
		_voiceRate.setExtraIntervallStart(extraIntervallstart
				.getTimeIntervall());
		_voiceRate.setExtraFees(extraFees.getAmount());
		_voiceRate.setEndTime(endTimePicker.getTime());
		_voiceRate.setDureeMax(dureeMax.getTimeIntervall());
		_voiceRate.setDestinationZoneId(dest.getZoneId());
		_voiceRate.setDestinationProviderId(dest.getProviderId());
		_voiceRate.setDestinationCountryId(dest.getCountryId());
		_voiceRate.setDaysOfWeek(daysPickerView.getSelectedDays());
		_voiceRate.setConnectionCharges(connectionCharges.getAmount());
		_voiceRate.setDestinationLabel(dest.toString());

		TelecomCost.getDatabaseManager().saveData(VoiceRate.PROP_TYPE,
				TelecomCost.getGson().toJson(_voiceRate), _voiceRate.getId(),
				_voiceRate.hashCode());
		Toast.makeText(_context,_voiceRate.getId() == -1 ? "Voice rate saved !!!" : "Voice rate updated !!!", 3).show();
	}

	private void prepareViewDestination() {
		if (destinationView.getZoneSpinner().getZones() == null) {
			destinationView.getZoneSpinner().setAdapter(null);
		} else {
			if (destinationView.getZoneSpinner().getZones().size() == 0) {
				destinationView.getZoneSpinner().setAdapter(null);
			}
		}

		setTitle("Voice rate Destination");
		btnNext.setText("Save");

		if (_voiceRate != null) {
//			destinationView.setDestination(_voiceRate.getDestinationZoneId(),
//					_voiceRate.getDestinationCountryId(),
//					_voiceRate.getDestinationProviderId());
		}
	}

	private boolean checkExtraTariff() {
		if (dureeMax.getTimeIntervall().getOccurence() <= 0) {
			Toast.makeText(_context,
					"Please set the max lenght for this tariff", 3).show();
			return false;
		}

		if (extraIntervallstart.getTimeIntervall().getOccurence() <= 0) {
			Toast.makeText(_context,
					"Please set the extra free time for this tariff", 3).show();
			return false;
		}

		if (extraTariffingIntervall.getTimeIntervall().getOccurence() <= 0) {
			Toast.makeText(_context,
					"Please set the extra tariffing intervall for this tariff",
					3).show();
			return false;
		}

		if (extraFees.getAmount() < 0) {
			Toast.makeText(_context,
					"Please set the extra fees for this tariff", 3).show();
			return false;
		}

		return true;
	}

	private void prepareViewExtraCharges() {
		setTitle("Voice rate extra fees");
		if (_voiceRate != null) {
			dureeMax.setTimeIntervall(_voiceRate.getDureeMax());
			extraIntervallstart.setTimeIntervall(_voiceRate
					.getExtraIntervallStart());
			extraTariffingIntervall.setTimeIntervall(_voiceRate
					.getExtraTariffingIntervall());
			extraFees.setAmount(_voiceRate.getExtraFees());
		}
	}

	protected void showPreviousView() {
		switch (viewIndex) {
		case VIEW_CHARGES:
			setTitle("Voice rate Dates");
			flipper.showPrevious();
			viewIndex--;
			break;
		case VIEW_EXTRA_TARIFF:
			setTitle("Voice rate fees");
			flipper.showPrevious();
			viewIndex--;
			break;
		case VIEW_DESTINATION:
			setTitle("Voice extra fees");
			flipper.showPrevious();
			viewIndex--;
			break;
		}
	}

	private void prepareViewCharges() {
		setTitle("Voice rate fees");
		fees.setLabel("Fees every " + tariffingIntervallView.toString() + " :");

		if (_voiceRate != null) {
			fees.setAmount(_voiceRate.getFees());
			connectionCharges.setAmount(_voiceRate.getConnectionCharges());
			minimumCharges.setAmount(_voiceRate.getMinimumCharges());
			maximumCharges.setAmount(_voiceRate.getMaximumCharges());
		} else {
			freeTimeView.setTimeIntervall();
			tariffingIntervallView.setTimeIntervall();
		}
	}

	private boolean checkDates() {
		if (!daysPickerView.daysOfWeekSet()) {
			Toast.makeText(_context, "Please set the days of the weeks", 3)
					.show();
			return false;
		}

		if (!startTimePicker.isTimeSet()) {
			Toast.makeText(
					_context,
					"Please fill in the start time of the tariff in selected days",
					3).show();
			return false;
		}

		if (!endTimePicker.isTimeSet()) {
			Toast.makeText(
					_context,
					"Please fill in the end time of the tariff in selected days",
					3).show();
			return false;
		}

		if (!freeTimeView.isTimeIntervallSet()) {
			Toast.makeText(_context,
					"Please specify the free time of this rate", 3).show();
			return false;
		}

		if (!tariffingIntervallView.isTimeIntervallSet()) {
			Toast.makeText(_context,
					"Please specify the tariffing intervall of this rate", 3);
			return false;
		}

		return true;
	}

	protected void closeDialog() {
		Log.i("VoiceRateWizard", "closing the VoiceRateWizard");
		hide();
		VoiceRateListActivity activity = (VoiceRateListActivity) _context;
		activity.bindVoiceRates();
	}

	@Override
	public void show() {
		Log.i("VoiceRateWizard", "showing the dialog...");
		ShowFirstView();
		super.show();
		Log.i("VoiceRateWizard", "VoiceRateWizard on screen...");
		if (_voiceRate != null) {
			bindVoiceRate(_voiceRate);
		}
	}

	private void ShowFirstView() {
		switch (viewIndex) {
		case VIEW_DATES:			
			break;
		case VIEW_CHARGES:
			flipper.showPrevious();
			viewIndex--;
			break;
		case VIEW_EXTRA_TARIFF:
			flipper.showPrevious();
			viewIndex--;
			flipper.showPrevious();
			viewIndex--;
			break;
		case VIEW_DESTINATION:
			flipper.showPrevious();
			viewIndex--;
			flipper.showPrevious();
			viewIndex--;
			flipper.showPrevious();
			viewIndex--;
			break;
		}
	}

	private void bindVoiceRate(VoiceRate _voiceRate) {
		if (_voiceRate != null) {
			startTimePicker.setTime(_voiceRate.getStartTime());
			endTimePicker.setTime(_voiceRate.getEndTime());
			freeTimeView.setTimeIntervall(_voiceRate.getIntervallstart());
			tariffingIntervallView.setTimeIntervall(_voiceRate
					.getTariffingIntervall());
			daysPickerView.setSelectedDays(_voiceRate.getDaysOfWeek());
		}		
	}

	@Override
	protected void onStart() {
		Log.i("VoiceRateWizard", "Starting the VoiceRateWizard...");
		super.onStart();
		Log.i("VoiceRateWizard", "VoiceRateWizard started...");
	}

	@Override
	protected void onStop() {
		Log.i("VoiceRateWizard", "Stopping the VoiceRateWizard...");
		super.onStop();
		Log.i("VoiceRateWizard", "VoiceRateWizard stopped...");
	}
}
